﻿using Microsoft.Extensions.Options;
using Mrc.Config;
using Mrc.Config.Messages;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Mrc.RabbitMQ
{
    public class RabbitmqPublish : IRabbitmqPublish
    {
        private readonly IConnectionPool _connectionPool;
        private readonly ISerializer _serializer;
        private string _itemName;
        private string _exchange;
        private string _queue;
        private string _routingKey;

        public RabbitmqPublish(IConnectionPool connectionPool,IOptions<MrcConfigOptions> mrcConfigOptions,ISerializer serializer)
        {
            this._serializer = serializer;
            _connectionPool = connectionPool;
            _itemName = mrcConfigOptions.Value.ItemName;
            _exchange = $"{_connectionPool.Exchange}.{_itemName}";
            _queue = $"mrc.queue.{_itemName}.log";
            _routingKey = $"mrc.queue.{_itemName}.*";
        }
        public void Publish(string msg)
        {
            throw new NotImplementedException();
        }

        public async void SendConfigMsg(ConfigMessages messages)
        {
            IModel channel = null;
            try
            {
                channel = _connectionPool.Rent();
                channel.ExchangeDeclare(_exchange,ExchangeType.Fanout,false);
                messages.ItemName = _itemName;
                channel.BasicPublish(_exchange,_routingKey,null,Encoding.UTF8.GetBytes(await _serializer.SerializeAsync(messages)));
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }
            finally
            {
                if (channel != null)
                {
                    var returned = _connectionPool.Return(channel);
                    if (!returned)
                    {
                        channel.Dispose();
                    }
                }
            }
        }


    }
}
